use tonic::transport::Server;
use crate::grpc_server::LogService;
use crate::storage::{LogStorage, create_storage};
use crate::config::load_config;
use crate::proto::log_service_server::LogServiceServer;
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::fmt().init();
    
    // 加载配置
    let config = load_config()?;
    
    // 创建存储
    let storage = create_storage(&config)?;
    
    // 启动后台刷新任务
    let storage_clone = storage.clone();
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(
            Duration::from_secs(config.storage.flush_interval)
        );
        
        loop {
            interval.tick().await;
            if let Err(e) = storage_clone.flush().await {
                error!("Failed to flush storage: {}", e);
            }
        }
    });
    
    // 创建gRPC服务
    let service = LogService::new(storage);
    let addr: SocketAddr = format!("{}:{}", config.server.host, config.server.port).parse()?;
    
    info!("Starting gRPC server on {}", addr);
    
    // 启动服务
    Server::builder()
        .add_service(LogServiceServer::new(service))
        .serve(addr)
        .await?;
    
    Ok(())
}